/* eslint-disable @typescript-eslint/no-unused-vars */
// import { Footer } from '@/components';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { FormattedMessage, history, SelectLang, useIntl, useModel, Helmet } from '@umijs/max';
import { Alert, Button, Card, Form, Input, message, Popconfirm, Tabs } from 'antd';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import { loginAPI } from '@/services/auth';
import { setToken } from '@/utils/tools';
import { Layout, Modal } from 'antd';
import '../Login/login.css';
const { Header, Sider, Content } = Layout;

const Lang = () => {
  const langClassName = useEmotionCss(({ token }) => {
    return {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  return (
    <div className={langClassName} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  /**
   * 模态框显示与隐藏
   */
  const [isShow, setIsShow] = useState(false);

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });

  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      const msg = await loginAPI({
        userName: values.username,
        password: values.password,
      });
      if (msg.success) {
        setToken(msg.data);
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
      return;
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status, type: loginType } = userLoginState;

  const headerStyle: React.CSSProperties = {
    textAlign: 'center',
    color: '#fff',
    height: 100,
    paddingInline: 50,
    lineHeight: '100px',
    // backgroundColor: '#7dbcea',
    backgroundImage:
      'url(https://img2.baidu.com/it/u=2375747515,3760330765&fm=253&fmt=auto&app=138&f=JPEG?w=960&h=350)',
    backgroundSize: '100% 100%',
  };

  const contentStyle: React.CSSProperties = {
    textAlign: 'center',
    minHeight: 120,
    lineHeight: '120px',
    color: '#fff',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundImage:
      "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
    backgroundSize: '100% 100%',
  };

  const siderStyle: React.CSSProperties = {
    textAlign: 'center',
    lineHeight: '120px',
    color: '#fff',
    backgroundColor: '#3ba0e9',
    backgroundImage:
      'url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202006%2F16%2F20200616153924_jShJW.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1687940392&t=b4c0452005bcaf24073c142a6206892a)',
    backgroundSize: '100% 100%',
  };

  return (
    <div className={containerClassName}>
      <Layout>
        <Sider width="480px" style={siderStyle}></Sider>
        <Layout>
          <Header style={headerStyle}>
            <p
              style={{
                fontSize: '50px',
                fontFamily: '楷体',
                color: 'black',
              }}
            >
              欢迎登录系统管理后台
            </p>
            <Lang />
          </Header>
          <Content style={contentStyle}>
            <Lang />
            <div
              style={{
                width: '600px',
                height: '500px',
                position: 'relative',
              }}
            >
              <div className="loginLeft"></div>
              <div className="loginRight"></div>
              <Card
                style={{
                  // boxShadow: '0px 0px 4px 2px gray',
                  width: '600px',
                  height: '500px',
                }}
              >
                <LoginForm
                  contentStyle={{
                    minWidth: 280,
                    maxWidth: '75vw',
                  }}
                  logo={<img alt="logo" src="/logo.svg" />}
                  title="医疗管理系统后台"
                  subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
                  initialValues={{
                    autoLogin: true,
                  }}
                  onFinish={async (values) => {
                    await handleSubmit(values as API.LoginParams);
                  }}
                >
                  <Tabs
                    activeKey={type}
                    onChange={setType}
                    centered
                    items={[
                      {
                        key: 'account',
                        label: intl.formatMessage({
                          id: 'pages.login.accountLogin.tab',
                          defaultMessage: '账户密码登录',
                        }),
                      },
                    ]}
                  />{' '}
                  {status === 'error' && loginType === 'account' && (
                    <LoginMessage
                      content={intl.formatMessage({
                        id: 'pages.login.accountLogin.errorMessage',
                        defaultMessage: '账户或密码错误(admin/ant.design)',
                      })}
                    />
                  )}
                  {type === 'account' && (
                    <>
                      <ProFormText
                        name="username"
                        fieldProps={{
                          size: 'large',
                          prefix: <UserOutlined />,
                        }}
                        placeholder={intl.formatMessage({
                          id: 'pages.login.username.placeholder',
                          defaultMessage: '用户名: admin or user',
                        })}
                        rules={[
                          {
                            required: true,
                            message: (
                              <FormattedMessage
                                id="pages.login.username.required"
                                defaultMessage="请输入用户名!"
                              />
                            ),
                          },
                        ]}
                      />
                      <ProFormText.Password
                        name="password"
                        fieldProps={{
                          size: 'large',
                          prefix: <LockOutlined />,
                        }}
                        placeholder={intl.formatMessage({
                          id: 'pages.login.password.placeholder',
                          defaultMessage: '请输入密码',
                        })}
                        rules={[
                          {
                            required: true,
                            message: (
                              <FormattedMessage
                                id="pages.login.password.required"
                                defaultMessage="请输入密码！"
                              />
                            ),
                          },
                        ]}
                      />
                    </>
                  )}
                  {/* <div
                    style={{
                      marginBottom: 20,
                      overflow: 'hidden',
                    }}
                  >
                    <Button onClick={() => setIsShow(true)}>忘记密码？</Button>
                    <Modal
                      title="模态框"
                      destroyOnClose={true}
                      maskClosable={false}
                      open={isShow}
                      footer={null}
                      onOk={() => {
                        setIsShow(false);
                      }}
                      onCancel={() => setIsShow(false)}
                    >
                      <Card>
                        <Form
                          preserve={false}
                          onFinish={(v) => {
                            console.log(v);
                          }}
                        >
                          <Form.Item
                            label="用户名"
                            name="userName"
                            rules={[
                              {
                                required: true,
                                message: '请输入用户名',
                              },
                            ]}
                          >
                            <Input placeholder="请输入用户名"></Input>
                          </Form.Item>
                          <Form.Item
                            label="密　码"
                            name="password"
                            rules={[
                              {
                                required: true,
                                message: '请输入密码',
                              },
                            ]}
                          >
                            <Input placeholder="请输入密码"></Input>
                          </Form.Item>
                          <Form.Item>
                            <Button type="primary" htmlType="submit" block>
                              提交
                            </Button>
                          </Form.Item>
                        </Form>
                      </Card>
                    </Modal>
                  </div> */}
                </LoginForm>
              </Card>
            </div>
          </Content>
          {/* <Footer style={footerStyle}>Footer</Footer> */}
        </Layout>
      </Layout>
      {/* <Lang />
      <Card
        style={{
          boxShadow: '0px 0px 4px 2px gray',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="医疗管理系统后台"
          subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: intl.formatMessage({
                  id: 'pages.login.accountLogin.tab',
                  defaultMessage: '账户密码登录',
                }),
              },
            ]}
          />{' '}
          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误(admin/ant.design)',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '用户名: admin or user',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 10,
              overflow: 'hidden',
            }}
          >
            <a
              style={{
                float: 'left',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a>
          </div>
        </LoginForm>
      </Card> */}
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
